PYTHON MAIN FUNCTION is a starting point of any
program. When the program is run, the python interpreter runs the code
sequentially. Main function is executed only when it is run as a Python
program. It will not run the main function if it imported as a module.
def main():
print ("hello world!")
print ("Python")
print ("hello world!")
print ("Python")
Here, we got two pieces of print- one is defined within the main
function that is "Hello World" and the other is independent, which is
"Python". When you run the function def main ():
- Only "Python" prints out
- and not the code "Hello World."
It is because we did not declare the call function "if__name__== "__main__". It is important that after defining the main function, you call the code by if__name__== "__main__" and then run the code, only then you will get the output "hello world!" in the programming console. Consider the following code
def main():
print("hello world!")
if __name__ == "__main__":
main()
print("Python")
- When Python interpreter reads a source file, it will execute all the code found in it.
- When Python runs the "source file" as the main program, it sets the special variable (__name__) to have a value ("__main__").
- When you execute the main function, it will then read the "if" statement and checks whether __name__ does equal to __main__.
- In Python "if__name__== "__main__" allows you to run the Python files either as reusable modules or standalone programs.
The __name__ variable and Python Module
def main():
print("hello world!")
if __name__ == "__main__":
main()
print("Python ")
print("Value in built variable name is: ",__name__)
No comments:
Post a Comment